package com.cookor.poi.modules.weixin.web;

import com.cookor.poi.common.web.BaseController;
import com.cookor.poi.modules.phy.entity.TWeixinUser;
import com.cookor.poi.modules.phy.service.TWeixinUserService;
import com.cookor.poi.modules.sys.utils.MobileUtils;
import com.cookor.poi.modules.weixin.account.Account;
import com.cookor.poi.modules.weixin.account.WeixinException;
import com.cookor.poi.modules.weixin.entity.TWeixinConfig;
import com.xiaoleilu.hutool.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2021年04月23日 10:37
 */
@Controller
public class WeiXinAppController extends BaseController{

    @Autowired
    private TWeixinUserService tWeixinUserService;

    @RequestMapping(value = "/wx/oauth")
    public RedirectView Oauth(HttpServletRequest request,
                              HttpServletResponse response, Model model)
            throws UnsupportedEncodingException, InvocationTargetException,
            WeixinException {

        Map<String, Object> sessionMap = (Map<String, Object>) MobileUtils
                .getSessionValue();
        String code = request.getParameter("code");
        String uniacid = request.getParameter("i");
        String tenantId = request.getParameter("siteId");
        if (StringUtils.isBlank(uniacid) || StringUtils.isBlank(code)) {
            System.out.println("通信错误，请在微信中重新发起请求");
            return null;
            // return "通信错误，请在微信中重新发起请求";
        }
        Account account = Account.factory(uniacid);
        JSONObject jo = account.getOauthInfo(code);
        String openid = jo.getStr("openid");
        String dest_url = URLDecoder.decode(sessionMap.get("dest_url")
                .toString(), "utf-8");
        sessionMap.put("openid", openid);

        if(StringUtils.isNotBlank(openid)){
            TWeixinUser user = tWeixinUserService.getByOpenId(openid);
            if(user == null){
                jo = account.getUserInfo(openid);
                user = jo.toBean(TWeixinUser.class);
                user.setUniacid(Integer.parseInt(tenantId));
                tWeixinUserService.save(user);
            }
        }

        MobileUtils.setSessionValue(sessionMap);
        RedirectView view = new RedirectView(dest_url);
        view.setExposeModelAttributes(false);
        return view;
    }

}
